package com.kld.third.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.kld.common.framework.dto.ResultMsg;
import com.kld.third.api.jingdong.IJdAreaService;
import com.kld.third.dto.jingdong.JDArea;
import com.kld.third.dto.jingdong.constant.JDConstant;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * Created by dara on 2016/3/28.
 */
@Service
public class JdAreaServiceImpl implements IJdAreaService {

    @Autowired
    private JdBaseServiceImpl jdBaseService;
    private Logger logger = LoggerFactory.getLogger(JdAreaServiceImpl.class);

    @Override
    public List<JDArea> getProvinceList() {
        String jso =  jdBaseService.returnMsg(JDConstant.URL_AREA_PROVINCE,"");
        return formatAddrToJsonArray(jso);
    }

    @Override
    public List<JDArea> getCityList(Integer provinceid) {
        String jso =  jdBaseService.returnMsg(JDConstant.URL_AREA_CITY,provinceid.toString());
        return formatAddrToJsonArray(jso);
    }

    @Override
    public List<JDArea> getCountyList(Integer cityid) {
        String jso =  jdBaseService.returnMsg(JDConstant.URL_AREA_COUNTY,cityid.toString());
        return formatAddrToJsonArray(jso);
    }

    @Override
    public List<JDArea> getTownList(Integer countyid) {
        String jso =  jdBaseService.returnMsg(JDConstant.URL_AREA_TOWN,countyid.toString());
        return formatAddrToJsonArray(jso);
    }



    //返回
    public List<JDArea> formatAddrToJsonArray(String jsonStr) {
        List<JDArea> jdAreas = new ArrayList<JDArea>();
        if (jsonStr.startsWith("{") && jsonStr.endsWith("}")) {
            JSONObject jsonObject = JSONObject.fromObject(jsonStr);
            if (jsonObject.toString().length() > 0) {
                try {
                    for (Iterator iter = jsonObject.keys(); iter.hasNext(); ) {
                        String key = iter.next().toString();
                        JDArea area = new JDArea();
                        area.setId(jsonObject.getInt(key));
                        area.setName(jsonObject.getString(key));
                       jdAreas.add(area);
                    }
                } catch (Exception ex) {
                    logger.error("京东地址解析异常",ex.getMessage(),ex);
                }
            }
        }
        return jdAreas;
    }
}
